package com.chj.exchange.direct;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 队列和交换器的多重绑定
 */
public class MultiBindConsumer {
    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("10.200.169.5");
        connectionFactory.setVirtualHost("chj_vhost");
        connectionFactory.setUsername("chj");
        connectionFactory.setPassword("123456");
        // 创建连接
        Connection connection = connectionFactory.newConnection();
        final Channel channel = connection.createChannel();
        // 在信道中设置交换器
        channel.exchangeDeclare(DirectProducer.EXCHANGE_NAME, BuiltinExchangeType.DIRECT);
        // 声明一个随机队列
        String queueName = channel.queueDeclare().getQueue();
        // TODO：队列绑定到交换器上时，是允许绑定多个路由键的，也就是多重绑定
        String[] routeKeys ={"hankin01","hankin02","hankin03"};
        for(String routeKey : routeKeys){
            channel.queueBind(queueName, DirectProducer.EXCHANGE_NAME, routeKey);
        }
        System.out.println(" [*] Waiting for messages:");
        // 创建队列消费者
        final DefaultConsumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope,
                                       AMQP.BasicProperties properties,
                                       byte[] body) throws IOException {
                String message = new String(body,"UTF-8");
                System.out.println("Received["+envelope.getRoutingKey()+"]"+message);
            }
        };
        // TODO 消息者正是开始在指定队列上消费。这里第二个参数是自动确认参数，如果是true则是自动确认
        channel.basicConsume(queueName,true,consumer);
    }
}
